<template>
  <div class="w-full h-full">
    <canvas ref="chartRef"></canvas>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, watch } from 'vue'
  import {
    Chart as ChartJS,
    ArcElement,
    Tooltip,
    Legend,
    CategoryScale,
    LinearScale,
    BarElement,
    Title,
    LineElement,
    PointElement
  } from 'chart.js'

  // 注册 Chart.js 组件
  ChartJS.register(
    ArcElement,
    Tooltip,
    Legend,
    CategoryScale,
    LinearScale,
    BarElement,
    Title,
    LineElement,
    PointElement
  )

  const props = {
    type: {
      type: String,
      default: 'line',
      validator: (value) => {
        return ['line', 'bar', 'horizontalBar', 'doughnut', 'pie', 'gauge'].includes(value)
      }
    }
  }

  const chartRef = ref(null)
  let chartInstance = null

  // 生成随机数据
  const generateData = () => {
    const baseValue = 100
    const dataPoints = 12

    return Array.from({ length: dataPoints }, () => {
      return Math.floor(baseValue + Math.random() * baseValue * 2)
    })
  }

  // 生成图表配置
  const getChartConfig = () => {
    const labels = [
      '1月',
      '2月',
      '3月',
      '4月',
      '5月',
      '6月',
      '7月',
      '8月',
      '9月',
      '10月',
      '11月',
      '12月'
    ]
    const data = generateData()
    const backgroundColors = [
      'rgba(59, 130, 246, 0.7)', // 蓝色
      'rgba(16, 185, 129, 0.7)', // 绿色
      'rgba(249, 115, 22, 0.7)', // 橙色
      'rgba(139, 92, 246, 0.7)', // 紫色
      'rgba(239, 68, 68, 0.7)' // 红色
    ]

    const borderColors = backgroundColors.map((color) => color.replace('0.7', '1'))

    switch (props.type) {
      case 'line':
        return {
          type: 'line',
          data: {
            labels,
            datasets: [
              {
                label: '数值趋势',
                data,
                borderColor: borderColors[0],
                backgroundColor: `${backgroundColors[0]}80`,
                tension: 0.3,
                fill: true
              }
            ]
          },
          options: getCommonOptions()
        }

      case 'bar':
        return {
          type: 'bar',
          data: {
            labels,
            datasets: [
              {
                label: '数值分布',
                data,
                backgroundColor: backgroundColors[0],
                borderColor: borderColors[0],
                borderWidth: 1
              }
            ]
          },
          options: getCommonOptions()
        }

      case 'horizontalBar':
        return {
          type: 'bar',
          data: {
            labels: [
              '产品A',
              '产品B',
              '产品C',
              '产品D',
              '产品E',
              '产品F',
              '产品G',
              '产品H',
              '产品I',
              '产品J'
            ],
            datasets: [
              {
                label: '销量',
                data: generateData()
                  .slice(0, 10)
                  .sort((a, b) => a - b),
                backgroundColor: backgroundColors[1],
                borderColor: borderColors[1],
                borderWidth: 1
              }
            ]
          },
          options: {
            ...getCommonOptions(),
            indexAxis: 'y'
          }
        }

      case 'doughnut':
        return {
          type: 'doughnut',
          data: {
            labels: ['华东', '华南', '华北', '西部', '东北'],
            datasets: [
              {
                data: [35, 25, 20, 15, 5],
                backgroundColor: backgroundColors.slice(0, 5),
                borderColor: borderColors.slice(0, 5),
                borderWidth: 1
              }
            ]
          },
          options: {
            ...getCommonOptions(),
            cutout: '65%'
          }
        }

      case 'pie':
        return {
          type: 'pie',
          data: {
            labels: ['类别A', '类别B', '类别C', '类别D'],
            datasets: [
              {
                data: [40, 30, 20, 10],
                backgroundColor: backgroundColors.slice(0, 4),
                borderColor: borderColors.slice(0, 4),
                borderWidth: 1
              }
            ]
          },
          options: getCommonOptions()
        }

      case 'gauge':
        // 模拟仪表盘
        const value = Math.floor(Math.random() * 60) + 20 // 20-80之间的随机值
        return {
          type: 'doughnut',
          data: {
            datasets: [
              {
                data: [value, 100 - value],
                backgroundColor: [
                  value > 70
                    ? backgroundColors[4]
                    : value > 50
                      ? backgroundColors[2]
                      : backgroundColors[1],
                  'rgba(50, 50, 50, 0.2)'
                ],
                borderWidth: 0
              }
            ]
          },
          options: {
            ...getCommonOptions(),
            cutout: '80%',
            rotation: -90,
            circumference: 180,
            plugins: {
              tooltip: {
                enabled: false
              },
              legend: {
                display: false
              },
              title: {
                display: true,
                text: `${value}%`,
                color: '#e5e7eb',
                font: {
                  size: 24,
                  weight: 'bold'
                },
                padding: {
                  bottom: 10
                }
              }
            }
          }
        }

      default:
        return {
          type: 'line',
          data: {
            labels,
            datasets: [
              {
                label: '数值趋势',
                data,
                borderColor: borderColors[0],
                backgroundColor: `${backgroundColors[0]}80`,
                tension: 0.3,
                fill: true
              }
            ]
          },
          options: getCommonOptions()
        }
    }
  }

  // 通用图表配置
  const getCommonOptions = () => {
    return {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        x: {
          grid: {
            color: 'rgba(100, 100, 100, 0.1)'
          },
          ticks: {
            color: 'rgba(200, 200, 200, 0.7)'
          }
        },
        y: {
          grid: {
            color: 'rgba(100, 100, 100, 0.1)'
          },
          ticks: {
            color: 'rgba(200, 200, 200, 0.7)'
          }
        }
      },
      plugins: {
        legend: {
          labels: {
            color: 'rgba(200, 200, 200, 0.7)'
          }
        },
        tooltip: {
          backgroundColor: 'rgba(30, 30, 30, 0.8)',
          titleColor: '#e5e7eb',
          bodyColor: '#e5e7eb',
          borderColor: 'rgba(100, 100, 100, 0.3)',
          borderWidth: 1
        }
      },
      animation: {
        duration: 1000,
        easing: 'easeOutQuart'
      }
    }
  }

  // 创建图表
  const createChart = () => {
    if (chartRef.value) {
      // 如果已有图表实例，先销毁
      if (chartInstance) {
        chartInstance.destroy()
      }

      // 创建新图表
      chartInstance = new ChartJS(chartRef.value, getChartConfig())
    }
  }

  // 监听图表类型变化
  watch(
    () => props.type,
    () => {
      createChart()
    }
  )

  // 组件挂载时创建图表
  onMounted(() => {
    createChart()

    // 定时更新图表数据
    const interval = setInterval(() => {
      if (chartInstance) {
        chartInstance.data.datasets.forEach((dataset) => {
          dataset.data = generateData()
        })
        chartInstance.update()
      }
    }, 8000)

    // 清理函数
    return () => clearInterval(interval)
  })

  // 组件卸载时销毁图表
  onUnmounted(() => {
    if (chartInstance) {
      chartInstance.destroy()
    }
  })
</script>
